package com.wang.learrn.common.mybatis.handler;

import com.wang.learrn.common.mybatis.IEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 类描述：对于枚举值的处理handler
 *
 * @author Charles
 * @time 2021/9/29 17:22
 */
@MappedJdbcTypes({JdbcType.TINYINT})
public class CodeEnumTypeHandler<E extends Enum<E> & IEnum> extends BaseTypeHandler<E> {
    private Class<E> type;
    private E[] enums;

    /**
     * 构造函数，用于创建该handler，并检查传入的Enum是否符合规范
     * @param type
     */
    public CodeEnumTypeHandler(Class<E> type) {
        if(type==null){
            throw new IllegalArgumentException("Type argument cannot be null!");
        }else {
            this.type=type;
            if(type.isEnum()){
                this.enums = (E[])type.getEnumConstants();
                if(this.enums==null){
                    throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
                }
            }
        }

    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setByte(i, ((IEnum)parameter).code());
    }
    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        byte code = rs.getByte(columnName);

        return rs.wasNull()?null:this.ofCode(code);
    }
    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        byte code = rs.getByte(columnIndex);
        return rs.wasNull()?null:this.ofCode(code);
    }
    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        byte code = cs.getByte(columnIndex);
        return cs.wasNull()?null:this.ofCode(code);
    }

    /**
     * code 2 E
     * @param code
     * @return
     */
    private E ofCode(byte code){

        if(this.enums==null){
            return null;
        }else {
            E[] enm = this.enums;
            int length = enm.length;
            for (int i = 0; i < length; i++) {
                E e = enm[i];
                if(e.code()==code){
                    return e;
                }
            }
            return null;
        }
    }
}
